const state = {
  messages: [],
  onlineUsers: [],
  currentReceiver: null,
  websocket: null,
  connected: false
}

const mutations = {
  SET_MESSAGES: (state, messages) => {
    state.messages = messages
  },
  ADD_MESSAGE: (state, message) => {
    state.messages.push(message)
  },
  SET_ONLINE_USERS: (state, users) => {
    state.onlineUsers = users
  },
  SET_CURRENT_RECEIVER: (state, receiver) => {
    state.currentReceiver = receiver
  },
  SET_WEBSOCKET: (state, websocket) => {
    state.websocket = websocket
  },
  SET_CONNECTED: (state, connected) => {
    state.connected = connected
  }
}

const actions = {
  // 设置消息列表
  setMessages ({ commit }, messages) {
    commit('SET_MESSAGES', messages)
  },

  // 添加消息
  addMessage ({ commit }, message) {
    commit('ADD_MESSAGE', message)
  },

  // 设置在线用户
  setOnlineUsers ({ commit }, users) {
    commit('SET_ONLINE_USERS', users)
  },

  // 设置当前接收者
  setCurrentReceiver ({ commit }, receiver) {
    commit('SET_CURRENT_RECEIVER', receiver)
  },

  // 设置WebSocket连接
  setWebSocket ({ commit }, websocket) {
    commit('SET_WEBSOCKET', websocket)
  },

  // 设置连接状态
  setConnected ({ commit }, connected) {
    commit('SET_CONNECTED', connected)
  },

  // 发送消息
  sendMessage ({ state }, message) {
    if (state.websocket && state.connected) {
      state.websocket.send(JSON.stringify(message))
    }
  },

  // 断开连接
  disconnect ({ state, commit }) {
    if (state.websocket) {
      state.websocket.close()
      commit('SET_WEBSOCKET', null)
      commit('SET_CONNECTED', false)
    }
  }
}

const getters = {
  messages: state => state.messages,
  onlineUsers: state => state.onlineUsers,
  currentReceiver: state => state.currentReceiver,
  connected: state => state.connected
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
